package com.instant.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.instant.searcher.DocSearcher;
import com.instant.searcher.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


//指定当前路径与Servlet类相对应
@WebServlet("/searcher")
public class DocSearcherServlet extends HttpServlet {

    private static DocSearcher docSearcher = new DocSearcher();
    private ObjectMapper objectMapper = new ObjectMapper();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.先解析请求，拿到用户提交的查询词
        String query = request.getParameter("query");
        if(query==null||query.equals("")){
            String msg = "非法输入，没有获取query的值。";
            System.out.println(msg);
            response.sendError(404 , msg);
            return;
        }
        //2.打印记录query的值
        System.out.println("query:"+query);
        //3.调用搜索模块进行搜索
        List<Result> results = docSearcher.search(query);
        //4.把当前的搜索结果进行打包
        response.setContentType("application/json; charset=utf-8");
        objectMapper.writeValue(response.getWriter(), results);
    }
}
